from django.core.exceptions import ImproperlyConfigured
from django.db.transaction import commit_on_success
from django.db.models import fields, get_app
from django.http import Http404, HttpResponse
from database import memory_model, get_model, make_rdf_annotations
import dc, dct, dclite4g
import RDF

w3type = RDF.Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")

__all__ = ["rdf_import", "rdf_annotate"]

@commit_on_success
def rdf_import(request, app_label, module_name):
    django_model = get_model(app_label, module_name)
    if not hasattr(django_model._default_manager, "rdf_get_or_create"):
        raise Http404("no RDF implementation")

    model = memory_model(request.raw_post_data)

    s = RDF.Statement(None, w3type, dclite4g.DataSet.uri)
    for r in model.find_statements(s):
        print r
        # @@ workaround - inherit schema-mandatory properties from
        # Series, explicitly here. 
        model = _augment_model(model,r.subject)
        try:
            print "creating", r.subject
            django_model.objects.rdf_get_or_create(model, r.subject)
            # if suucessful, store the rdf annotations too.
            make_rdf_annotations(django_model,model)
        except Exception, e:
            print e
            raise

    
    return HttpResponse("OK")

def _augment_model(model,subject):
    for pred in [dc.title,dct.spatial]:

        object = None
        for s in model.find_statements(RDF.Statement(subject,pred.uri,None)):
            object = s.object
        if object is None:
            print "No %s found for DataSet %s"%(pred.uri,subject) 
            print "replacing DataSet %s"%(pred.uri)
                # sparql Q
            subj = str(subject)
            subj = subj.replace('[','<')
            subj = subj.replace(']','>')
            prop = '<'+str(pred.uri)+'>'
            
            query = """
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX dclite4g: <http://dclite4g.xmlns.com/schema.rdf#>
SELECT ?y {
%s dclite4g:series ?x . 
?x %s ?y
}"""%(subj,prop)
            print query
            for r in RDF.SPARQLQuery(query).execute(model):
                object = RDF.Node(r['y'])
                model.append(RDF.Statement(subject,pred.uri,object))  
    return model


@commit_on_success
def rdf_annotate(request, app_label, module_name):
    """Reads POSTed RDF/XML annotations into the RDF store.
    Looks for RDF extensions on Django class (module_name). 
    """
    django_model = get_model(app_label, module_name)
    if not hasattr(django_model._meta, "rdf"):
        raise Http404("no RDF implementation")

    storage = RDF.Storage(storage_name="memory", name="memory",
                  options_string="")
    model = RDF.Model(storage)
    parser = RDF.Parser()
    parser.parse_string_into_model(model, request.raw_post_data,
                       "http://www.example.com/")

    make_rdf_annotations(django_model,model)

    return HttpResponse("OK")

